import axios from 'axios'
import store from '../store'
import router from '../router/router'
import {getToken} from '@/util/auth'
import {Message} from 'element-ui'
import errorCode from '@/const/errorCode'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

// 超时时间
axios.defaults.timeout = 30000

// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true
NProgress.configure({showSpinner: false})// NProgress Configuration

// HTTP request拦截
axios.interceptors.request.use(config => {
  NProgress.start() // start progress bar
  if (store.getters.access_token) {
    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
  }
  return config
}, error => {
  return Promise.reject(error)
})

// HTTP response拦截
axios.interceptors.response.use(response => {
  NProgress.done()
  const res = response.data
  if (res.status === 'success') {
    if (res.data != null && res.data.total != null) {
      //解决服务端long变string的问题
      res.data.total = parseInt(res.data.total)
    }
    return res.data
  } else {
    return response
  }
}, error => {
  NProgress.done()
  const errMsg = error.toString()
  const code = errMsg.substr(errMsg.indexOf('code') + 5)
  Message({
    message: errorCode[code] || errorCode['default'],
    type: 'error'
  })

  if (parseInt(code) === 401) {
    store.dispatch('FedLogOut').then(() => {
      router.push({path: '/login'})
    })
  }

  return Promise.reject(new Error(error))
})

export default axios
